package drds.data_propagate.driver.packets.client.command_packet;

import drds.data_propagate.driver.packets.CommandPacket;
import drds.data_propagate.driver.utils.ByteHelper;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * COM_REGISTER_SLAVE
 */
public class RegisterSlavePacket extends CommandPacket {
    @Setter
    @Getter
    public String host;
    @Setter
    @Getter
    public int port;
    @Setter
    @Getter
    public String username;
    @Setter
    @Getter
    public String password;
    @Setter
    @Getter
    public long serverId;

    public RegisterSlavePacket() {
        setCommand((byte) 0x15);
    }


    public void decode(byte[] bytes) {
        // bypass
    }

    public byte[] encode() throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byteArrayOutputStream.write(getCommand());
        ByteHelper.writeUnsignedIntLittleEndian(serverId, byteArrayOutputStream);
        //
        byteArrayOutputStream.write((byte) host.getBytes().length);
        ByteHelper.writeFixedLengthBytesFromStart(host.getBytes(), host.getBytes().length, byteArrayOutputStream);
        //
        byteArrayOutputStream.write((byte) username.getBytes().length);
        ByteHelper.writeFixedLengthBytesFromStart(username.getBytes(), username.getBytes().length, byteArrayOutputStream);
        //
        byteArrayOutputStream.write((byte) password.getBytes().length);
        ByteHelper.writeFixedLengthBytesFromStart(password.getBytes(), password.getBytes().length, byteArrayOutputStream);
        //
        ByteHelper.writeUnsignedShortLittleEndian(port, byteArrayOutputStream);
        //
        ByteHelper.writeUnsignedIntLittleEndian(0, byteArrayOutputStream);// Fake
        // rpl_recovery_rank
        ByteHelper.writeUnsignedIntLittleEndian(0, byteArrayOutputStream);// master id
        return byteArrayOutputStream.toByteArray();
    }

}
